import React, {useEffect, useState} from "react";
import {Button, Card, Col, Form, Input, message, Modal, Row, Select, Space, Tabs} from "antd";
import CodeEditor from "@/components/CodeEditor";
import {configByEntity, generateApi} from "@/api/code";
import {getListProject, getProjectTemplate} from "@/api/project";
import {initConfig} from "@/config";

const CustomCode: React.FC = () => {
    const [result, setResult] = useState({});
    const [projectList, setProjectList] = useState<{ value: number, label: string }[]>([]);
    const [selectedProject, setSelectedProject] = useState<number>();
    const [visible, setVisible] = useState(false);
    const [entityUrl, setEntityUrl] = useState('com.lty.model.entity.User');
    const [binding, setBinding] = useState(JSON.stringify(initConfig, null, 2));

    useEffect(() => {
        fetchProjectList();
    }, []);

    useEffect(() => {
        if (projectList.length > 0) {
            const firstProjectId = projectList[0].value;
            setSelectedProject(firstProjectId);
            fetchProjectTemplateData(firstProjectId);
        }
    }, [projectList]);

    const handleChange = async (value) => {
        await fetchProjectTemplateData(value);
        setSelectedProject(value);
    };

    const fetchProjectTemplateData = async (id) => {
        if (!id) {
            message.error('请选择项目');
            return;
        }
        try {
            const res = await getProjectTemplate(id);
            const formattedResult = res.data.reduce((acc, item) => {
                acc[item.code] = ''; // 初始化每个code对应的值为空字符串
                return acc;
            }, {} as { [key: string]: string });
            setResult(formattedResult);
        } catch (error) {
            message.error('获取项目数据失败');
            console.error('获取项目数据失败:', error);
        }
    };

    const fetchCodeApi = async () => {
        try {
            const templates = Object.keys(result);
            let parsedBinding;
            try {
                parsedBinding = JSON.parse(binding);
            } catch (e) {
                message.error('绑定配置不是有效的 JSON');
                return;
            }
            const res = await generateApi({
                binding: parsedBinding,
                templates: templates
            });
            if (res.code === 0) {
                setResult(res.data);
            } else {
                message.error(res.message);
            }
        } catch (e) {
            message.error(e.message);
        }
    };

    const fetchProjectList = async () => {
        try {
            const res = await getListProject({});
            const result = res.data.map((item) => ({
                value: item.id,
                label: item.code
            }));
            setProjectList(result);
        } catch (error) {
            message.error('获取项目数据失败');
            console.error('获取项目数据失败:', error);
        }
    };

    const handleEntityUrl = async () => {
        try {
            const res = await configByEntity({
                str: entityUrl,
            })
            if (res.code === 0) {
                // 格式化
                setBinding(JSON.stringify(res.data, null, 2));
                message.success('读取配置成功');
            } else {
                message.error(res.message);
            }
        } catch (e) {
        } finally {
            setVisible(false)
        }
    };

    const getCodeConfig = () => (
        <div style={{display: 'flex', alignItems: 'center'}}>
            <p style={{margin: 0, marginRight: 8}}>选择项目模板</p>
            <Select style={{width: 150}} showSearch options={projectList} value={selectedProject}
                    onChange={handleChange}/>
        </div>
    );

    return (
        <div>
            <Row>
                <Col span={8}>
                    <Card title="绑定配置" extra={getCodeConfig()}>
                        <CodeEditor value={binding} language="json" onChange={(v) => setBinding(v)}/>
                        <Space style={{marginTop: 16}}>
                            <Button type="primary" onClick={fetchCodeApi}>生成代码</Button>
                            <Button onClick={()=>{setVisible(true);}}>本地路径</Button>
                        </Space>
                    </Card>
                </Col>
                <Col span={16}>
                    <Tabs type="card" items={Object.keys(result).map(key => ({
                        label: key,
                        key: key,
                        children: <CodeEditor value={result[key]} language="java" height={650}/>
                    }))}/>
                </Col>
            </Row>

            <Modal title="后端实体路径" visible={visible} onCancel={()=>{
                setVisible(false);
            }} onOk={handleEntityUrl}>
                <Input value={entityUrl} />
            </Modal>
        </div>
    );
};

export default CustomCode;